package org.jeecg.modules.aliyun.phone.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.aliyun.phone.Config;
import org.jeecg.modules.aliyun.phone.service.IPhoneService;
import org.jeecg.modules.demo.entity.Demo;
import org.jeecg.modules.demo.mapper.DemoMapper;
import org.jeecg.modules.phone.entity.CreateImgPamarsVo;
import org.jeecg.modules.phone.entity.PhoneOrderPamarsVo;
import org.jeecg.modules.phone.entity.UploadFilePamarsVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.cloudphone20201230.models.*;
import com.aliyun.sdk.service.cloudphone20201230.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import static java.lang.Thread.sleep;

/**
 * @Description: DemoDescript
 * @Author: jeecg-boot
 * @Date:   2022-08-09
 * @Version: V1.0
 */
@Service
public class PhoneServiceImpl extends ServiceImpl<DemoMapper, Demo> implements IPhoneService {

    String RegionID = "cn-hangzhou";
    String Endpoint = "cloudphone.cn-hangzhou.aliyuncs.com";

    @Override
    public String doSendTxtCommand(String InstanceIds, String commandStr) {
        commandStr = "adb shell am broadcast -a ADB_INPUT_TEXT --es msg '"+commandStr+"'" ;// commandStr +"c";

        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
            RunCommandRequest runCommandRequest = RunCommandRequest.builder()
                    .regionId(RegionID)
                    .instanceId(Arrays.asList(InstanceIds.split(",")))
                    .command(commandStr)
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();
            CompletableFuture<RunCommandResponse> response = client.runCommand(runCommandRequest);
            RunCommandResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            client.close();
//            RunCommandResponseBody body = resp.getBody();
            return new Gson().toJson(resp.getBody());

        } catch (Exception e) {
            log.error("执行命令失败:" + e.getMessage());
            return "执行命令失败!" + e.getMessage();
        }
    }
    @Override
    public String doRunCommand(String InstanceIds, String commandStr) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
            RunCommandRequest runCommandRequest = RunCommandRequest.builder()
                    .regionId(RegionID)
                    .instanceId(Arrays.asList(InstanceIds.split(",")))
                    .command(commandStr)
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();
            CompletableFuture<RunCommandResponse> response = client.runCommand(runCommandRequest);
            RunCommandResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            client.close();
//            RunCommandResponseBody body = resp.getBody();
            return new Gson().toJson(resp.getBody());

//            :com.doutui.bozhong
//            com.ss.android.ugc.aweme
//            adb shell am start com.ss.android.ugc.aweme/.main.MainActivity
//            adb shell am start com.doutui.bozhong/.wxapi.WXEntryActivity
//            adb shell input tap 660 1177  抖音我的
//            cpm-bp14thtbvv8k0u6uqm9p   公司母盘
        } catch (Exception e) {
            log.error("执行命令失败:" + e.getMessage());
            return "执行命令失败!" + e.getMessage();
        }
    }

    @Override
    public String doSendFile(UploadFilePamarsVo uploadFilePamarsVo) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
            // Parameter settings for API request
            SendFileRequest sendFileRequest = SendFileRequest.builder()
                    .instanceId(Arrays.asList(uploadFilePamarsVo.getInstanceId().split(",")))
                    .regionId(uploadFilePamarsVo.getRegionId())
                    .ossBucket(uploadFilePamarsVo.getOssBucket())
                    .ossObject(uploadFilePamarsVo.getOssObject())
                    .path(uploadFilePamarsVo.getPath())
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<SendFileResponse> response = client.sendFile(sendFileRequest);
            // Synchronously get the return value of the API request
            SendFileResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("发送文件失败:" + e.getMessage());
            return "发送文件失败!" + e.getMessage();
        }
    }

    @Override
    public String doInstallApplication(UploadFilePamarsVo uploadFilePamarsVo) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
            // Parameter settings for API request

            InstallApplicationRequest installApplicationRequest = InstallApplicationRequest.builder()
                    .instanceId(Arrays.asList(uploadFilePamarsVo.getInstanceId().split(",")))
                    .regionId(uploadFilePamarsVo.getRegionId())
                    .ossBucket(uploadFilePamarsVo.getOssBucket())
                    .ossObject(uploadFilePamarsVo.getOssObject())
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<InstallApplicationResponse> response = client.installApplication(installApplicationRequest);
            // Synchronously get the return value of the API request
            InstallApplicationResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("安装apk失败:" + e.getMessage());
            return "安装apk失败!" + e.getMessage();
        }
    }

    @Override
    public String doListInstanceVncUrl(UploadFilePamarsVo uploadFilePamarsVo) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
            // Parameter settings for API request
            // Parameter settings for API request
            ListInstanceVncUrlRequest listInstanceVncUrlRequest = ListInstanceVncUrlRequest.builder()
                    .instanceId(uploadFilePamarsVo.getInstanceId())
                    .regionId(uploadFilePamarsVo.getRegionId())
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<ListInstanceVncUrlResponse> response = client.listInstanceVncUrl(listInstanceVncUrlRequest);
            // Synchronously get the return value of the API request
            ListInstanceVncUrlResponse resp = response.get();

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("获取VNC失败:" + e.getMessage());
            return "获取VNC失败!" + e.getMessage();
        }
    }

    @Override
    public String doCreateImage(CreateImgPamarsVo createImgPamarsVo) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);

            // Parameter settings for API request
            CreateImageRequest createImageRequest = CreateImageRequest.builder()
                    .instanceId(createImgPamarsVo.getInstanceId())
                    .regionId(createImgPamarsVo.getRegionId())
                    .description(createImgPamarsVo.getDescription())
                    .imageName(createImgPamarsVo.getImageName())
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<CreateImageResponse> response = client.createImage(createImageRequest);
            // Synchronously get the return value of the API request
            CreateImageResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("创建IMG失败:" + e.getMessage());
            return "创建IMG失败!" + e.getMessage();
        }
    }

    @Override
    public String doListImages(CreateImgPamarsVo createImgPamarsVo) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);

            // Parameter settings for API request
            ListImagesRequest listImagesRequest = ListImagesRequest.builder()
                    .regionId("cn-hangzhou")
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<ListImagesResponse> response = client.listImages(listImagesRequest);
            // Synchronously get the return value of the API request
            ListImagesResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("獲取imgList失败:" + e.getMessage());
            return "獲取imgList失败!" + e.getMessage();
        }
    }

    @Override
    public String doRunInstances(PhoneOrderPamarsVo phoneOrderPamarsVo) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);

            RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder()
                    .imageId(phoneOrderPamarsVo.getImageId())
                    .amount(phoneOrderPamarsVo.getAmount())
                    .chargeType(phoneOrderPamarsVo.getChargeType())
                    .description(phoneOrderPamarsVo.getDescription())
                    .instanceName(phoneOrderPamarsVo.getInstanceName())
                    .instanceType(phoneOrderPamarsVo.getInstanceType())
                    .keyPairName(phoneOrderPamarsVo.getKeyPairName())
                    .regionId(phoneOrderPamarsVo.getRegionId())
                    .securityGroupId(phoneOrderPamarsVo.getSecurityGroupId())
                    .vSwitchId(phoneOrderPamarsVo.getVSwitchId())
                    .eipBandwidth(1)
                    .resolution("720*1280")    //720*1280 536*960
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<RunInstancesResponse> response = client.runInstances(runInstancesRequest);

            RunInstancesResponse resp = response.get();
            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("获取用户信息异常:" + e.getMessage());
            return "开启实例失败!" + e.getMessage();
        }


    }

//
//    @Override
//    public String doListRegions() throws ExecutionException, InterruptedException {
//
//        AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
//        ListRegionsRequest listRegionsRequest = ListRegionsRequest.builder().build();
//        CompletableFuture<ListRegionsResponse> response = client.listRegions(listRegionsRequest);
//        ListRegionsResponse resp = response.get();
//        client.close();
//        return new Gson().toJson(resp);
//    }
//
    @Override
    public String doFetchFile(String InstanceIds,String objcetFilePath,String path)   {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
            FetchFileRequest fetchFileRequest = FetchFileRequest.builder()
                    .regionId(RegionID)
                    .instanceId(InstanceIds)
                    .ossBucket("ylphone")
                    .ossObject(objcetFilePath)
                    .path(path)
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<FetchFileResponse> response = client.fetchFile(fetchFileRequest);
            // Synchronously get the return value of the API request
            FetchFileResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("下载文件异常:" + e.getMessage());
            return "下载文件异常!" + e.getMessage();
        }
    }



    @Override
    public String doListInstances(String InstanceIds) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);
            ListInstancesRequest listInstancesRequest = ListInstancesRequest.builder()
                    .regionId(RegionID)
                    .showWebRtcToken(true)
                    .instanceId(Arrays.asList(InstanceIds.split(",")))
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<ListInstancesResponse> response = client.listInstances(listInstancesRequest);
            // Synchronously get the return value of the API request
            ListInstancesResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("获取实例异常:" + e.getMessage());
            return "获取实例异常!" + e.getMessage();
        }


    }

    @Override
    public String StopInstances(String InstanceIds) {
        try {
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);

            List<String> instanceIdList = Arrays.asList(InstanceIds.split(","));

            // Parameter settings for API request
            StopInstancesRequest stopInstancesRequest = StopInstancesRequest.builder()
                    .regionId(RegionID)
                    .instanceId(instanceIdList)
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<StopInstancesResponse> response = client.stopInstances(stopInstancesRequest);
            // Synchronously get the return value of the API request
            StopInstancesResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("停止实例异常:" + e.getMessage());
            return "停止实例失败!" + e.getMessage();
        }

    }


    @Override
    public String doDeleteInstances(String InstanceIds) {
        try {
            String s = StopInstances(InstanceIds);
            System.out.println("停止结果：" + s);
            sleep(15000);
            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);

            List<String> instanceIdList = Arrays.asList(InstanceIds.split(","));

            // Parameter settings for API request
            DeleteInstancesRequest deleteInstancesRequest = DeleteInstancesRequest.builder()
                    .regionId(RegionID)
                    .instanceId(instanceIdList)
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<DeleteInstancesResponse> response = client.deleteInstances(deleteInstancesRequest);
            // Synchronously get the return value of the API request
            DeleteInstancesResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("删除实例失败:" + e.getMessage());
            return "" ;
        }

    }

    @Override
    public String doDeleteImages(String imageIds) {
        try {

            AsyncClient client = getAsyncClient(getStaticCredentialProvider(), RegionID, Endpoint);

            List<String> instanceIdList = Arrays.asList(imageIds.split(","));

            // Parameter settings for API request
            DeleteImagesRequest deleteImagesRequest = DeleteImagesRequest.builder()
                    .regionId(RegionID)
                    .imageId(instanceIdList)
                    //                    Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<DeleteImagesResponse> response = client.deleteImages(deleteImagesRequest);
            // Synchronously get the return value of the API request
            DeleteImagesResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

            client.close();
            return new Gson().toJson(resp.getBody());
        } catch (Exception e) {
            log.error("删除实例失败:" + e.getMessage());
            return "删除实例失败!" + e.getMessage();
        }

    }



    private AsyncClient getAsyncClient(StaticCredentialProvider provider, String RegionID, String Endpoint) {
        AsyncClient client = AsyncClient.builder()
                .region(RegionID) // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(Endpoint)
                )
                .build();
        return client;
    }

    @NotNull
    private StaticCredentialProvider getStaticCredentialProvider() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(Config.accessKeyId)
                .accessKeySecret(Config.accessKeySecret)
                //.securityToken("<your-token>") // use STS token
                .build());
        return provider;
    }

}
